//
//  NewInfoViewController.m
//  Korea
//
//  Created by 崔剑 on 15/8/27.
//  Copyright (c) 2015年 KoreaGo. All rights reserved.
//

#import "NewInfoViewController.h"
#import "Header.h"
#import <ShareSDK/ShareSDK.h>
#import "LoginViewController.h"
#import "Recommend.h"
#import "CorrDataManager.h"
#import "Collection.h"
#import "UMSocial.h"
@interface NewInfoViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *infoNewWebView;
@property (nonatomic, strong) UIView *lowerView;
@property (nonatomic, strong) UIView *borderView;
@property (nonatomic, assign) BOOL transiting;
@property (nonatomic, strong) CorrDataManager *manager;
@property (nonatomic ,strong) MBProgressHUD *HUD;
@property (nonatomic, strong) UIButton *praiseButton;
@property (nonatomic, assign) BOOL likeFlag;

@end

@implementation NewInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [CorrDataManager shareCoreDataManager];
    
    // Do any additional setup after loading the view.
    self.title = self.recommend.title;
    self.view.backgroundColor = [UIColor colorWithRGB:0xf3f4f8 alpha:1];
    self.navigationController.navigationBar.translucent = NO;
    
    // 初始化webView
    self.infoNewWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113)];
    NSString *linkStr = self.linkStr;

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:linkStr]];
    self.infoNewWebView.delegate = self;
    [self.view addSubview:self.infoNewWebView];
    [self.infoNewWebView loadRequest:request];
    
    // 返回键
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRGB:0xfe868f  alpha:1];
    
    // 分享
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"infoshare@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRGB:0xfe868f  alpha:1];
    
    
    self.lowerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height - 45 , self.view.width, 60)];
    self.lowerView.backgroundColor = [UIColor whiteColor];
    self.lowerView.userInteractionEnabled = YES;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.lowerView];


    self.borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, self.view.width, 1)];
    self.borderView.backgroundColor = [UIColor colorWithRGB:0xc8c7cc alpha:1];
    self.borderView.userInteractionEnabled = YES;
    [self.lowerView addSubview:self.borderView];
  
    
    // 点赞按钮
    self.praiseButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.praiseButton.frame = CGRectMake(25, 6.5, 35, 35);
    [self.praiseButton setBackgroundImage:[UIImage imageNamed:@"praise@2x.png"] forState :UIControlStateNormal];
    [self.praiseButton addTarget:self action:@selector(addPraiseAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.lowerView addSubview:self.praiseButton];
    
    // 收藏
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    collectButton.frame = CGRectMake(self.view.width / 3 * 2 - 40, 7.5, self.view.width / 3 + 20, 30);
    [collectButton setBackgroundImage:[UIImage imageNamed:@"addcollection1@2x.png"] forState:UIControlStateNormal];
    [collectButton addTarget:self action:@selector(addCollectionAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.lowerView addSubview:collectButton];
    

    // 获取通知中心对象, 是一个单例
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    // 注册一个观察事件
    [center addObserver:self selector:@selector(receiveNotification:) name:@"changeColor" object:nil];
    
}


- (void)receiveNotification:(NSNotification *)notification
{
    NSLog(@"----%@", notification.object);
    [self.praiseButton setBackgroundImage:[UIImage imageNamed:notification.object] forState:UIControlStateNormal];
    
}

- (void)addPraiseAction:(UIButton *)button
{
    // 点赞
    if (self.likeFlag == NO) {
        
        [self.praiseButton setBackgroundImage:[UIImage imageNamed:@"praise2@2x.png"] forState:UIControlStateNormal];
        self.likeFlag =! self.likeFlag;
        
    } else {
        
        [self.praiseButton setBackgroundImage:[UIImage imageNamed:@"praise@2x.png"] forState:UIControlStateNormal];
        self.likeFlag =! self.likeFlag;
        
    }
    
}

- (void)addCollectionAction:(UIButton *)button
{
    
    // 收藏
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *token = [user valueForKey:@"userInfo"];
    if (token == nil) {
        LoginViewController *login = [[LoginViewController alloc] init];
        
        login.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:nil];
    } else{
        
        Collection *collectionModel = [NSEntityDescription insertNewObjectForEntityForName:@"Collection" inManagedObjectContext:self.manager.managedObjectContext];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Collection" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        
        // Specify criteria for filtering which objects to fetch
        NSString *str = [NSString stringWithFormat:@"url CONTAINS '%@'", self.linkStr];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
        [fetchRequest setPredicate:predicate];
        // Specify how the fetched objects should be sorted
//        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"url"
//                                                                       ascending:YES];
//        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            collectionModel.title = self.recommend.title;
            collectionModel.url = self.linkStr;
            collectionModel.image = self.recommend.image;
            [self.manager saveContext];
            self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self.HUD.mode = MBProgressHUDModeText;
            self.HUD.color = [UIColor blackColor];
            self.HUD.alpha = 0.5;
            self.HUD.minSize = CGSizeMake(BASEWIDTH * 9, BASEWIDTH * 6);
            self.HUD.labelText = @"收藏成功";
            self.HUD.dimBackground = YES;
        }
        
    }
    
    
    
}

- (void)leftAction:(UIBarButtonItem *)button
{
    // 返回
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)rightAction:(UIBarButtonItem *)button
{
    // 分享
//    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
//    
//    //构造分享内容
//    id<ISSContent> publishContent = [ShareSDK content:@"分享内容"
//                                       defaultContent:@"测试一下"
//                                                image:[ShareSDK imageWithPath:imagePath]
//                                                title:@"ShareSDK"
//                                                  url:@"http://www.mob.com"
//                                          description:@"这是一条测试信息"
//                                            mediaType:SSPublishContentMediaTypeNews];
//    //创建弹出菜单容器
//    id<ISSContainer> container = [ShareSDK container];
//    //    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
//    
//    //弹出分享菜单
//    [ShareSDK showShareActionSheet:container
//                         shareList:nil
//                           content:publishContent
//                     statusBarTips:YES
//                       authOptions:nil
//                      shareOptions:nil
//                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
//                                
//                                if (state == SSResponseStateSuccess)
//                                {
//                                    NSLog(@"分享成功");
//                                }
//                                else if (state == SSResponseStateFail)
//                                {
//                                    NSLog(@"分享失败,错误码:%ld,错误描述:%@", [error errorCode], [error errorDescription]);
//                                }
//                            }];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    //选择白色
    UIColor * color = [UIColor blackColor];
    
    //设置颜色
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];

    self.tabBarController.tabBar.hidden = YES;
    
    self.lowerView.hidden = NO;
}


- (void)viewWillDisappear:(BOOL)animated{

    self.lowerView.hidden = YES;
    //选择白色
    UIColor * color = [UIColor whiteColor];
    
    //设置颜色
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRGB:0xfe868f alpha:YES];
    
    self.tabBarController.tabBar.hidden = NO;
}


@end
